package cn.ubeta.b2c.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiUser;
import cn.ubeta.b2c.bean.UserInfo;
import cn.ubeta.b2c.utils.AppConfig;
import cn.ubeta.b2c.utils.NetworkCallback;
import cn.ubeta.b2c.utils.ToastHelper;
import java.io.IOException;

/**
 * Created by denny on 16/9/5.
 */

public class LoginActivity extends ThirdPartyLoginActivity implements View.OnClickListener, TextWatcher {

    public static final String PARAMS_CB_ACTIVITY = "cb_activity";
    public static final String PARAMS_CB_EXTRAS = "cb_extras";

    private EditText mEtPhone;
    private EditText mEtPswd;
    private TextView mTvLogin;

    // 验证码
    private View mLayoutAuth;
    private EditText authcodeText;
    private ImageView authcodeImage;
    private String curauthcodeUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_login);

        //TitleBarHelper.setRightAction(this, "注册", v -> gotoRegister());

        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mEtPswd = (EditText) findViewById(R.id.et_pswd);
        mTvLogin = (TextView) findViewById(R.id.tv_login);
        mLayoutAuth = findViewById(R.id.ll_auth_code);

        mEtPhone.addTextChangedListener(this);
        mEtPswd.addTextChangedListener(this);

        mTvLogin.setOnClickListener(this);

        initVerifyCode();
    }

    /**
     * 初始化验证码
     */
    private void initVerifyCode() {
        authcodeText = (EditText) findViewById(R.id.tv_auth_code);
        authcodeImage = (ImageView) findViewById(R.id.iv_auth_code);
        /*
        authcodeImage.setOnClickListener(view -> helper.refreshAuthCode(curauthcodeUrl, new OnNeedImageCodeCallBack(){

            @Override
            public void onSuccess(PicDataInfo picDataInfo) {
                ByteArrayInputStream in = new ByteArrayInputStream(picDataInfo.getsPicData());
                authcodeImage.setImageDrawable(Drawable.createFromStream(in, "tackpic"));
            }

            @Override
            public void onFail(FailResult failResult) {

            }
        }));

        //前置
        helper.isNeedImageCode(new OnNeedImageCodeCallBack(){
            @Override
            public void onSuccess(PicDataInfo picDataInfo) {
                refreshAutoCode(picDataInfo);
            }

            @Override
            public void onFail(FailResult failResult) {
            }
        });
        */
    }

    /**
     * 刷新验证码
     * @param picDataInfo
     */
    /*
    private void refreshAutoCode(PicDataInfo picDataInfo) {
        if(picDataInfo != null && !TextUtils.isEmpty(picDataInfo.getsPicURL())){
            //显示验证码图片
            mLayoutAuth.setVisibility(View.VISIBLE);

            ByteArrayInputStream in = new ByteArrayInputStream(picDataInfo.getsPicData());
            authcodeImage.setImageDrawable(Drawable.createFromStream(in, "tackpic"));
            curauthcodeUrl = picDataInfo.getsPicURL();
        } else {
            //不显示验证码图片
            mLayoutAuth.setVisibility(View.GONE);
        }
    }
    */

    /**
     * 跳转到注册页面
     */
    private void gotoRegister() {
        RegisterActivity.gotoActivity(this, RegisterActivity.class);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.tv_login == id) {
            startLogin();
        } else if (R.id.tv_register == id) {
            LoginActivity.gotoActivity(this, RegisterActivity.class);
        } else if (R.id.tv_forgot_pswd == id) {
            // TODO 忘记密码
        }
    }

    /**
     * 开始登录
     */
    private void startLogin() {
        String username = mEtPhone.getEditableText().toString();
        String password = mEtPswd.getEditableText().toString();
        String authcode = authcodeText.getEditableText().toString();

        if (TextUtils.isEmpty(username)) {
            ToastHelper.show("请输入用户名");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            ToastHelper.show("请输入密码");
            return;
        }

        if (mLayoutAuth.getVisibility() == View.VISIBLE && TextUtils.isEmpty(authcode)) {
            ToastHelper.show("请输入验证码");
            return;
        }

        mTvLogin.setEnabled(false);

        ApiUser.login(username, password, new NetworkCallback<UserInfo>() {
            @Override
            public void onResponse(UserInfo info) {
                AppConfig.saveUserInfo(info);
                onLoginSuccess();
            }

            @Override
            public void onFailure(IOException e) {
                ToastHelper.show("登录失败：" + e.getMessage());
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean enable = !TextUtils.isEmpty(mEtPhone.getEditableText().toString()) &&
                !TextUtils.isEmpty(mEtPswd.getEditableText().toString());
        mTvLogin.setEnabled(enable);
    }

    /**
     * 登录成功
     */
    private void onLoginSuccess() {
        String clazzName = getIntent().getStringExtra(PARAMS_CB_ACTIVITY);
        if (!TextUtils.isEmpty(clazzName)) {
            Class clazz = null;
            try {
                clazz = Class.forName(clazzName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (clazz != null) {
                Intent intent = new Intent(this, clazz);
                Bundle extras = getIntent().getBundleExtra(PARAMS_CB_EXTRAS);
                if (extras != null) {
                    intent.putExtras(extras);
                }
                startActivity(intent);
                overridePendingTransition(R.anim.in_right_to_left, android.R.anim.fade_out);
            } else {
                ToastHelper.show("登录错误");
            }
        }
        setResult(RESULT_OK);
        finish();
    }
}
